﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace TST.DemoCode.EventReceivers
{
    public class FoldersToFields : SPItemEventReceiver
    {
        private SPItemEventProperties _properties;
        List<String> _fieldNames = new List<string>();

        public override void ItemAdded(SPItemEventProperties properties)
        {
            _properties = properties;
            TranslateFoldersToFields();
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            _properties = properties;
            TranslateFoldersToFields();
        }

        public override void ItemFileMoved(SPItemEventProperties properties)
        {
            _properties = properties;
            TranslateFoldersToFields();
        }

        private void GetFieldNames()
        {
            _fieldNames.Clear();
            if (_properties.ListItem.ContentType != null && _properties.ListItem.ContentType.Parent != null)
            {
                SPContentType contentType = _properties.ListItem.ContentType.Parent;
                SPWeb parentWeb = contentType.ParentWeb;
                String key = FoldersToFields.GetSetupPropertyKey(contentType);
                if (parentWeb.AllProperties.ContainsKey(key))
                {
                    if (parentWeb.AllProperties[key] != null && !String.IsNullOrEmpty(parentWeb.AllProperties[key].ToString()))
                    {
                        String[] names = parentWeb.AllProperties[key].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < names.Length; i++)
                        {
                            _fieldNames.Add(names[i]);
                        }
                    }
                }
            }
        }

        private void TranslateFoldersToFields()
        {
            if (_properties == null || _properties.ListItem == null || _properties.ListItem.File == null)
            {
                return;
            }
            GetFieldNames();

            // Initialize objects.
            SPFolder itemFolder = _properties.ListItem.File.ParentFolder;
            List<String> folders = new List<String>();

            // Get folder hierarchy for the current item.
            SPFolder parent = itemFolder;
            while (parent != null && parent.UniqueId != _properties.ListItem.ParentList.RootFolder.UniqueId)
            {
                folders.Insert(0, parent.Name);
                parent = parent.ParentFolder;
            }

            bool modified = false;

            for (int i = 0; i < _fieldNames.Count; i++)
            {
                if (_properties.ListItem.Fields.ContainsField(_fieldNames[i]))
                {
                    if (i < folders.Count && !String.IsNullOrEmpty(folders[i]))
                    {
                        if (_properties.ListItem[_fieldNames[i]] == null || _properties.ListItem[_fieldNames[i]].ToString() != folders[i])
                        {
                            _properties.ListItem[_fieldNames[i]] = folders[i];
                            modified = true;
                        }
                    }
                    else
                    {
                        // Reset the value if no folder was used for this field.
                        if (_properties.ListItem[_fieldNames[i]] != null)
                        {
                            _properties.ListItem[_fieldNames[i]] = null;
                            modified = true;
                        }
                    }
                }
            }

            if (modified)
            {
                DisableEventFiring();
                try
                {
                    _properties.ListItem.SystemUpdate(false);                    
                }
                finally
                {
                    EnableEventFiring();
                }
            }
        }

        public static String GetSetupPropertyKey(SPContentType contentType)
        {
            String key = String.Format("FTF_{0}", contentType.Id.ToString());
            return key.ToLower(); // AllProperties are always stored in lower case by SharePoint
        }

        internal static bool SupportsFoldersToFields(SPContentType contentType)
        {
            foreach (SPEventReceiverDefinition def in contentType.EventReceivers)
            {
                if (String.Compare(def.Class, typeof(FoldersToFields).FullName, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
